﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using GoShopping.Model;
using GoShopping.Model.Enumerations;

namespace GoShopping.BLL
{
    /// <summary>
    /// Membership操作类
    /// </summary>
    public class MemberShipService
    {
        /// <summary>
        /// 数据库中是否有用户数据
        /// </summary>
        /// <returns></returns>
        public bool IsMembershipDBHasData()
        {
            int memCount = Convert.ToInt32(Databases.DBGoShoppingMember.Select(GoShoppingMembershipNBear.aspnet_Users, GoShoppingMembershipNBear.aspnet_Users.UserId.Count()).ToDataSet().Tables[0].Rows[0][0].ToString());
            if (memCount > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取所有Membetship中的成员
        /// </summary>
        /// <returns></returns>
        public IList<MembershipUser> GetAllMembers()
        {
            IList<MembershipUser> list = new List<MembershipUser>();
            System.Collections.ICollection arr = Membership.GetAllUsers();
            foreach (MembershipUser m in arr)
            {
                list.Add(m);
            }
            arr = null;
            return list;
        }

        /// <summary>
        /// 验证用户
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool ValidateUser(string username, string password)
        {
            return Membership.ValidateUser(username, password);
        }

        /// <summary>
        /// 该用户名是否存在数据库中
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public bool IsUserInMembershipDB(string username)
        {
            MembershipUser mu = Membership.GetUser(username);
            if (mu == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 更改成员密码
        /// </summary>
        /// <param name="username"></param>
        /// <param name="oldPassword"></param>
        /// <param name="newPassword"></param>
        /// <returns></returns>
        public bool ChangeMemberPassword(string username, string oldPassword, string newPassword)
        {
            MembershipUser mu = Membership.GetUser(username);
            return mu.ChangePassword(oldPassword, newPassword);
        }

        /// <summary>
        /// 锁定或解锁用户
        /// [超级管理员不能锁定]
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="isApprove">True为批准,False为锁定</param>
        public void ApproveMember(string userName, bool isApprove)
        {
            MembershipUser mu = Membership.GetUser(userName);
            if (isApprove == true)//解锁
            {
                if (mu.IsLockedOut == false)
                {
                    mu.IsApproved = isApprove;
                }
            }
            else if (!Roles.IsUserInRole(Model.Enumerations.Member_Roles.Role_SuperManager.ToString()))
            {
                if (mu.IsLockedOut == false)
                {
                    mu.IsApproved = isApprove;
                }
            }
            Membership.UpdateUser(mu);
        }

        ///// <summary>
        ///// 获取成员所在的角色
        ///// [暂规定：一个成员只有一个角色]
        ///// [如果一个成员有多个角色，那么调用这个会抛出异常，如果到时业务需要，那就需要重写该方法]
        ///// </summary>
        ///// <param name="memberUserName"></param>
        ///// <returns></returns>
        //public Member_Roles GetMemberRole(string memberUserName)
        //{
        //    MembershipUser mu = Membership.GetUser(memberUserName);
        //    string[] roles = Roles.GetRolesForUser(memberUserName);
        //    if (roles.Length == 1)
        //    {
        //        Member_Roles r = (Member_Roles)Enum.Parse(typeof(Member_Roles), roles[0]);
        //        return r;
        //    }
        //    else
        //    {
        //        throw (new Exception("GetMemberRole Error!"));
        //    }
        //}

        /// <summary>
        /// 获取成员的角色列表
        /// </summary>
        /// <param name="memberUserName"></param>
        /// <returns></returns>
        public IList<Member_Roles> GetMemberRoleList(string memberUserName)
        {
            IList<Member_Roles> list = new List<Member_Roles>();
            MembershipUser mu = Membership.GetUser(memberUserName);
            string[] roles = Roles.GetRolesForUser(memberUserName);
            foreach (string s in roles)
            {
                Member_Roles r = (Member_Roles)Enum.Parse(typeof(Member_Roles), s);
                list.Add(r);
            }
            return list;
        }

        /// <summary>
        /// 获取一个角色下的用户
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public IList<MembershipUser> GetRoleUsers(Member_Roles role)
        {
            string[] usersName = Roles.GetUsersInRole(role.ToString());
            IList<MembershipUser> userList = new List<MembershipUser>();
            foreach (string s in usersName)
            {
                userList.Add(Membership.GetUser(s));
            }
            return userList;
        }

        /// <summary>
        /// 模糊查询这些用户信息
        /// </summary>
        /// <param name="strUserName"></param>
        /// <returns></returns>
        public IList<MembershipUser> GetMembers(string strUserName)
        {
            IList<UserInfo> userList = Databases.DBGoShopping.Select(
                GoShoppingNBear.UserInfo).Where(GoShoppingNBear.UserInfo.Name.Like("%" + strUserName + "%")).ToList<UserInfo>();
            IList<MembershipUser> list = new List<MembershipUser>();
            foreach (UserInfo u in userList)
            {
                list.Add(Membership.GetUser(u.Name));
            }
            return list;
        }


        /// <summary>
        /// 创建用户
        /// 会员，商品管理员，下载管理员等
        /// </summary>
        /// <param name="userName">Member用户</param>
        /// <param name="eMail"></param>
        /// <param name="password">密码</param>
        /// <param name="passwordQustion"></param>
        /// <param name="passwordanser">问题答案</param>
        /// <param name="IsApproved">是否批准</param>
        /// <param name="role">角色</param>
        /// <param name="createStatue">返回创建是否成功的状态</param>
        /// <returns>创建成功返回Ture，不成功返回False，同时createStatue表示不成功的原因</returns>
        public bool CreateMember(string userName, string eMail, string password, string passwordQustion, string passwordanser, bool IsApproved, Member_Roles role, out MembershipCreateStatus createStatue)
        {
            bool returnValue;
            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required))
            {
                MembershipUser user = Membership.CreateUser(userName, password, eMail, passwordQustion,
                    passwordanser, IsApproved,
                    out createStatue);
                if (createStatue == MembershipCreateStatus.Success)
                {
                    Roles.AddUserToRole(user.UserName, role.ToString());
                    returnValue = true;
                }
                else
                {
                    returnValue = false;
                    if (user != null)
                    {
                        DeleteMember(user.UserName);
                    }
                }
                //通过工厂模式将不同用户类型添加到基本库中
                if (returnValue == true)
                {
                    IMember member = Factory_Member.CreateMemberOption(role);
                    member.AddNewMember(user);
                }
                scope.Complete();
            }
            return returnValue;
        }

        /// <summary>
        /// 删除会员
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public bool DeleteMember(string userName)
        {
            bool returnValue;
            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required))
            {
                IList<Member_Roles> roleList = this.GetMemberRoleList(userName);
                returnValue = Membership.DeleteUser(userName);
                //通过工厂模式将不同用户类型添加到基本库中
                if (returnValue == true)
                {//删除这个成员关联的角色里面的数据
                    foreach (Member_Roles role in roleList)
                    {
                        IMember member = Factory_Member.CreateMemberOption(role);
                        member.DeleteMember(userName);
                    }
                }
                scope.Complete();
            }
            return returnValue;
        }

        /// <summary>
        /// 删除一个角色下的所有用户
        /// </summary>
        /// <param name="role"></param>
        private void DeleteRoleUsers(Member_Roles role)
        {
            string[] usernames = Roles.GetUsersInRole(role.ToString());
            foreach (string user in usernames)
            {
                Membership.DeleteUser(user);
            }
        }

        #region 网站初始化

        /// <summary>
        /// 配置一个针对Email的超级管理员帐号
        /// 使用事务
        /// </summary>
        /// <param name="email"></param>
        /// <param name="emailPassword"></param>
        /// <param name="statue"></param>
        /// <returns></returns>
        public bool CreateSuperManager(string emailUserName, string emailPassword, out MembershipCreateStatus statue)
        {
            bool returnValue;
            //使用事务
            using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required))
            {
                DeleteRoleUsers(Member_Roles.Role_SuperManager);

                string UserName = emailUserName;
                string Email = emailUserName;
                string PasswordQuestion = "Email?";
                this.CreateMember(UserName, emailUserName, emailPassword, PasswordQuestion, emailUserName, true, Member_Roles.Role_SuperManager, out statue);
                if (statue == MembershipCreateStatus.Success)
                {
                    returnValue = true;
                }
                else
                {
                    returnValue = false;
                }

                scope.Complete();
            }//using scope
            return returnValue;
        }
        #endregion
    }
}
